/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel.tutorials.fileupload;

import cn.webwheel.Action;
import cn.webwheel.utils.WebParam;
import cn.webwheel.utils.fileupload.FileInfo;
import cn.webwheel.utils.fileupload.FileUploadExceptionAware;
import cn.webwheel.utils.fileupload.FileUploadSettings;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;

import java.io.File;

@FileUploadSettings(sizeMax = 100*1024)
public class FileUploadAction implements Action, FileUploadExceptionAware {

    @WebParam("file")
    public File file;

    @WebParam("file")
    public FileInfo fileInfo;

    @WebParam("param")
    public String param;

    private String msg;

    public String execute() throws Exception {
        if (msg != null) {
            return msg;
        }
        if (fileInfo == null) {
            return "上传文件为空";
        }
        // 返回上传文件的文件名到浏览器
        return fileInfo.getFileName() + "\nparam:" + param;
    }

    public void occur(FileUploadException e) {
        if (e instanceof FileUploadBase.SizeLimitExceededException) {
            msg = "上传文件过大";
        }
    }
}
